package pl.prv.polanie.client;

import java.util.List;

import pl.prv.polanie.client.compositerequest.PCompositeRequestBuilder;
import pl.prv.polanie.client.dialogs.CreateSemesterDialog;
import pl.prv.polanie.client.dialogs.CreateSubjectEventDialog;
import pl.prv.polanie.client.dto.CSGroupDTO;
import pl.prv.polanie.client.dto.CSLecturerDTO;
import pl.prv.polanie.client.dto.CSSemesterDTO;
import pl.prv.polanie.client.dto.CSSemestersYearGroupsDTO;
import pl.prv.polanie.client.dto.CSVGroupDTO;
import pl.prv.polanie.client.dto.CSVLecturerDTO;
import pl.prv.polanie.client.dto.CSVSemesterDTO;
import pl.prv.polanie.client.model.Cache;
import pl.prv.polanie.client.model.ContextSettings;
import pl.prv.polanie.client.model.CookiesSettings;
import pl.prv.polanie.client.model.ServiceHolder;
import pl.prv.polanie.client.model.ViewDataProvider;
import pl.prv.polanie.client.panels.DatabaseVP;
import pl.prv.polanie.client.panels.SchedulesList;
import pl.prv.polanie.client.panels.SemesterSelectionTreeWidget;
import pl.prv.polanie.client.panels.tabpanel.MinimizableSimplePanel;
import pl.prv.polanie.client.panels.tabpanel.MinimizableTabPanel;
import pl.prv.polanie.client.panels.widgets.CSLecturerHTML;
import pl.prv.polanie.client.panels.widgets.CSObjectHTML;
import pl.prv.polanie.client.widgets.CustomDialogBox;
import pl.prv.polanie.client.widgets.Loader;
import pl.prv.polanie.client.widgets.LoaderBackground;
import pl.prv.polanie.client.widgets.LoaderSizes;
import pl.prv.polanie.client.widgets.SelectBoxWithObjects;
import pl.prv.polanie.client.widgets.Sorter;
import pl.prv.polanie.client.widgets.layout.logging.LogPanel;
import pl.prv.polanie.client.widgets.layout.splitpanels.JPHorizontalSplitPanel;
import pl.prv.polanie.client.widgets.layout.splitpanels.JPVerticalSplitPanel;
import pl.prv.polanie.client.widgets.layout.tooltip.ToolTip;
import pl.prv.polanie.client.widgets.schedule.Schedule;
import pl.prv.polanie.client.widgets.schedule.ScheduleUtil;
import pl.prv.polanie.client.widgets.schedule.ScheduleView;
import pl.prv.polanie.client.widgets.schedule.custom.LoginPanel;
import pl.prv.polanie.client.widgets.schedule.custom.SignInWidgets;
import pl.prv.polanie.client.widgets.schedule.widgets.DraggableZone;
import pl.prv.polanie.client.widgets.table.TableSubjectEvents;

import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.core.client.GWT;
import com.google.gwt.http.client.Request;
import com.google.gwt.http.client.RequestBuilder;
import com.google.gwt.http.client.RequestCallback;
import com.google.gwt.http.client.RequestException;
import com.google.gwt.http.client.Response;
import com.google.gwt.user.client.DOM;
import com.google.gwt.user.client.Element;
import com.google.gwt.user.client.Event;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.WindowResizeListener;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.AbsolutePanel;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.ChangeListener;
import com.google.gwt.user.client.ui.ClickListener;
import com.google.gwt.user.client.ui.DecoratedStackPanel;
import com.google.gwt.user.client.ui.DecoratedTabPanel;
import com.google.gwt.user.client.ui.FlexTable;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.HasHorizontalAlignment;
import com.google.gwt.user.client.ui.HorizontalPanel;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.MouseListenerAdapter;
import com.google.gwt.user.client.ui.RootPanel;
import com.google.gwt.user.client.ui.ScrollPanel;
import com.google.gwt.user.client.ui.SimplePanel;
import com.google.gwt.user.client.ui.TabPanel;
import com.google.gwt.user.client.ui.Tree;
import com.google.gwt.user.client.ui.TreeItem;
import com.google.gwt.user.client.ui.TreeListener;
import com.google.gwt.user.client.ui.VerticalPanel;
import com.google.gwt.user.client.ui.Widget;
import com.google.gwt.xml.client.Document;
import com.google.gwt.xml.client.NamedNodeMap;
import com.google.gwt.xml.client.Node;
import com.google.gwt.xml.client.NodeList;
import com.google.gwt.xml.client.XMLParser;

/**
 * Entry point classes define <code>onModuleLoad()</code>.
 */
public class Planner implements EntryPoint {
	
	private final int TOP_HTML_HEIGHT = 100;
	private final int STACK_PANEL_WIDTH = 200;
	
//	private final String STYLE_MAINVSP = "my-MainVSP";
	private final String STYLE_TOPHTML = "my-TopHTML";
//	private final String STYLE_MAINHSP = "my-MainHSP";
	
	
	//////////////////////////////////////////////////////////////
	private JPVerticalSplitPanel mainVSP = new JPVerticalSplitPanel();

	//////////////////////////////////////////////////////////////
	HTML topHTML = new HTML("<b>Selected semester:</b>");
	AbsolutePanel topAP = new AbsolutePanel();
	VerticalPanel topVP = new VerticalPanel();
	SelectBoxWithObjects contextSemesterSB = new SelectBoxWithObjects();
	
//	private static JPHorizontalSplitPanel mainHSP = new JPHorizontalSplitPanel();
	private static JPHorizontalSplitPanel mainHSP = new JPHorizontalSplitPanel();
	private static MinimizableTabPanel tabPanel = new MinimizableTabPanel();
	
	private boolean isItFirstRebuildingGUI = true;
	
	
	private DecoratedStackPanel stackPanel = new DecoratedStackPanel() {
		@Override
		public void setHeight(String height) {
			super.setHeight(height);
			
			String pixelHeightS = height.split("px")[0];
			
			int pixelHeight = Integer.parseInt(pixelHeightS);
			
			int widgetCount = stackPanel.getWidgetCount();
			
			for (int i = 0; i < widgetCount; i++) {
				Widget w = stackPanel.getWidget(i);
				w.setHeight((pixelHeight - (31 * widgetCount + 2)) + "px");
			}
		}
		
		@Override
		public void setWidth(String width) {
			super.setWidth(width);
			
			String pixelWidthS = width.split("px")[0];
			
			int pixelWidth = Integer.parseInt(pixelWidthS);
			
			for (int i = 0; i < stackPanel.getWidgetCount(); i++) {
				Widget w = stackPanel.getWidget(i);
				w.setWidth((pixelWidth - 2) + "px");
			}
			
		}
	};
	private DatabaseVP databaseVP = new DatabaseVP();
	
	private SchedulesList schedulesList = null;
	
	//references to tooltip displayed in application
	private static ToolTip displayedToolTip = null;
	
	
	private static LogPanel logger = null; 
	
	private static Planner planner;
	
	private static LoaderBackground mainLoaderBackground = null;
	private static LoaderBackground fadingLoader = null;
	
	private static WindowResizeListener windowResizeListener = null;
	
	
	private static SignInWidgets signInWidgets = null;
	

	
//	public void onModuleLoad() {
//		PCompositeRequestTest crt = new PCompositeRequestTest();
//		crt.test2();
//	}
	
	/**
	 * This is the entry point method.
	 */
	public void onModuleLoad() {
		planner = this;
		
//		Queue<String> q = new PriorityQueue<String>();
//		q.
		
//		testJPHorizontalSplitPanel();
//		testJPVerticalSplitPanel();
		
//		driTest();
//		treeWidget();
		
//		DialogBox db = new DialogBox(false, true);
//		db.setText("TSTTTTT ");
//		db.setWidget(new Label("asdasdasdasdasdsdas"));
//		
//		db.center();
		
//		testy();

		
		RequestBuilder rBuilder = new RequestBuilder(RequestBuilder.GET, "planner.cfg.xml");
//		rBuilder.setHeader("Cache-Control", "no-cache");
		//Cache-Control: no-cache
//		Cache-Control	max-age=5
		RequestCallback rCallback = new RequestCallback() {
			public void onError(Request request, Throwable exception) {
				Planner.log("Planner.downloadingCfg onError: " + exception.getMessage());
			};
			public void onResponseReceived(Request request, Response response) {
				
//				<planner-configuration>
//					<property name="debug_mode">
//						true
//					</property>
//				</planner-configuration>
				
				parsePlannerCfgDoc(response);
				
				boolean firstTimeStartup = true;
				rebuildGUI("Loading. Please wait...", firstTimeStartup);
				
			}
			/**
			 * @param response
			 */
			private void parsePlannerCfgDoc(Response response) {
				Document doc = XMLParser.parse(response.getText());
				Node plannerCfgNode = doc.getFirstChild();
				
				boolean guiDebugMode = false;
				boolean firebugDebugMode = false;
				
//				Window.alert(response.getText());
				
				NodeList propertiesList =  plannerCfgNode.getChildNodes();
				for (int i = 0; i < propertiesList.getLength(); i++) {
					Node n = propertiesList.item(i);
					if (n.getNodeName().equals("property")) {
						NamedNodeMap nnm = n.getAttributes();
						Node nameN = nnm.getNamedItem("name");
						if (nameN.getNodeValue().equals("gui_debug_mode")) {
							NodeList nl = n.getChildNodes();
							for (int j = 0; j < nl.getLength(); j++) {
								Node valueN = nl.item(j);
								if (valueN.getNodeType() == Node.TEXT_NODE) {
									String dm = valueN.getNodeValue().trim();
									Boolean b = new Boolean(dm);
									guiDebugMode = b.booleanValue();
								}
							}
						} else if (nameN.getNodeValue().equals("firebug_debug_mode")) {
							NodeList nl = n.getChildNodes();
							for (int j = 0; j < nl.getLength(); j++) {
								Node valueN = nl.item(j);
								if (valueN.getNodeType() == Node.TEXT_NODE) {
									String dm = valueN.getNodeValue().trim();
									Boolean b = new Boolean(dm);
									firebugDebugMode = b.booleanValue();
								}
							}
						}
					}
				}
				Planner.log("[ GUI DEBUG MODE ] " + guiDebugMode);
				Planner.log("[ FIREBUG DEBUG MODE ] " + firebugDebugMode);
				ContextSettings.setGuiDebugMode(guiDebugMode);
				ContextSettings.setFirebugDebugMode(firebugDebugMode);
			};
		};
		
		rBuilder.setCallback(rCallback);
		try {
			rBuilder.send();
		} catch (RequestException e) {
			Planner.log("Planner.onModuleLoad: " + "error while reading planner.cfg.xml file.");
			boolean firstTimeStartup = true;
			rebuildGUI("Loading. Please wait...", firstTimeStartup);
		}
		
		
		//
		
//		loadLoginForm();
//		
//		AcademicTitleForm atf = new AcademicTitleForm();
//		atf.center();
		
		
//		testDecoratedTabPanel();
//		treeTest();
//		tabsTest();
		
		
		
//		testSelectBox();
		
//		testFlexTablePerformance();
		
//		testRMB();
		
		//PomocniczeProby.testOnMouseInFF();
//		PomocniczeProby.testSEEditionWidget();
		
		
		
		
		
//		scheduleTest();
		
//		testSortableTable();
//		PomocniczeProby.testPreferenceTypeChooserWidget();
		
		
//		PomocniczeProby.testEventPreview();
		
//		PomocniczeProby.testOnBrowserEvent();
		
//		widgetPositionTest();
//		eventOverWidgetTest();
		
		
//		createDeclarationDialog();
		
//		testWidgetResizing();
//		testHSPInTabPanel();
		
		
	}
	
	public void loadLoginForm() {
		LoginPanel loginPanel = new LoginPanel(){
			@Override
			protected void runOnHidingWidget() {
				super.runOnHidingWidget();
				hideFading();
			}
		};
//		loginPanel.setDraggingEnabled(false);
		fadeWidgetWithMsg(null, false, loginPanel);
//		loginPanel.center();
//		RootPanel.get().add(loginPanel, 10, 10);
	}

	public void testy(){
//		Test.main(null);
		
	}
	
	public void testSelectBox() {
		SelectBoxWithObjects sb = new SelectBoxWithObjects();
		sb.addItem("NIE MOZNA WYBRAC ", null);
		for (int j = 0; j < 20; j++) {
			sb.addItem("obiekt " + j, null);
		}
		
		sb.setWidth("150px");
		
		sb.setSelectedIndex(3);
		RootPanel.get().add(sb, 100, 100);
	}
	
	public void testFlexTablePerformance() {
		Button renderFTButton = new Button("ft");
		renderFTButton.addClickListener(new ClickListener() {
			public void onClick(Widget sender) {
				
				FlexTable ft = new FlexTable();
				ft.setBorderWidth(1);
				for (int i = 0; i < 100; i++) {
					for (int j = 0; j < 10; j++) {
						ft.setWidget(i, j, new Label("row: " + i + ", col: " + j));
					}
				}
				
				RootPanel.get().add(ft);
			}
		});
		RootPanel.get().add(renderFTButton);
	}
	
	public void testSortableTable() {
		final TableSubjectEvents tse = new TableSubjectEvents(null);
		tse.loadData();
		RootPanel.get().add(tse);
	}
	
	public void widgetPositionTest() {
		
		final HTML html = new HTML("przekladowa kontrolka");
		html.setHeight("300px");
		html.setStyleName("test");
		
		final ScrollPanel sp = new ScrollPanel(html);
		sp.setHeight(100+"px");
		sp.setWidth("500px");
		
		html.addMouseListener(new MouseListenerAdapter() {
			public void onMouseEnter(Widget sender) {
				super.onMouseEnter(sender);
				
				Planner.log("Day.getAbsoluteTOP " + html.getAbsoluteTop());

				Planner.log ("Day.getAbsoluteTop2 " + DOM.getAbsoluteTop(html.getElement()));
				
				Planner.log("Day. DOM.getElementPropertyInt(w.getElement(), 'scrollTop') " + DOM.getElementPropertyInt(html.getElement(), "scrollTop") );
				Planner.log("Window.getScrollTop() " + Window.getScrollTop());

				Planner.log("Day. DOM.getElementPropertyInt(w.getElement(), 'scrollTop') do SP " + DOM.getElementPropertyInt(sp.getElement(), "scrollTop") );
			}
		});
		

		
		
		RootPanel.get().add(sp, 100, 100);
		
		RootPanel.get().add(new HTML("asdasdas"), 100, 2000);
		
	}
	
	public void eventOverWidgetTest() {
//		HTML test
		final HTML test = new HTML("testowy HTML") {
//			@Override
			public void onBrowserEvent(Event event) {
				super.onBrowserEvent(event);
				switch (DOM.eventGetType(event)) {
				case Event.ONMOUSEMOVE:
					if (ScheduleUtil.eventOverWiget(getH(), event)) {
						Planner.log("Planner HTML jest nad kontrolka");
					};
					break;

				default:
					break;
				}
			}
			
			public HTML getH() {
				return this;
			}
		};
		test.setStyleName("test");
		test.setWidth("200px");
		test.setHeight("100px");
		
		RootPanel.get().add(test, 50, 50);
		
	}
	
	
	public void scheduleTest() {
		Cache.loadInitialData();

		final Schedule schedule = new Schedule(false, ScheduleView.GROUP);
		schedule.setFilterPropertyLecturerID(1);


		
		

//		Long groupID = new Long(1);
//		Long sem
//		
//		
//		SchedulesList.downloadCalendarDays(schedule, groupID, semesterID, downloadSubjectEvents, lecturerID, downloadLecturerPreferences)
//		SchedulesList.downloadCalendarDays(schedule, new Long(1), new Long(1), false);

		
		//test lecutrer pref
//		Long groupID = new Long(1);
		Long groupID = new Long(13);
//		Long semesterID = new Long(1);
		Long semesterID = new Long(3);
		boolean downloadSubjectEvents = true;
		Long lecturerID = new Long(1);
		boolean downloadLecturerPreferences = false;
		Long roomID = new Long(1);
		
		SimplePanel scheduleWrapper = new SimplePanel();
		
		
		SchedulesList.downloadCalendarDays(scheduleWrapper, schedule, groupID, semesterID, downloadSubjectEvents, lecturerID, downloadLecturerPreferences, roomID, null);
		
		
		
//		//test podzialu dla grupy
//		Long groupID = new Long(1);
//		Long semesterID = new Long(1);
//		boolean downloadSubjectEvents = true;
//		Long lecturerID = null;
//		boolean downloadLecturerPreferences = false;
//		
//		SimplePanel scheduleWrapper = new SimplePanel();
//		
//		scheduleWrapper.add(schedule);
//		
//		List list = TestDataProvider.getTestCalendarDays();
//		CSCalendarDayDTO[] csCDs = (CSCalendarDayDTO[])list.get(0);
//		CSVCalendarDayDTO[] csVCDs = (CSVCalendarDayDTO[])list.get(1);
//		
//		for (int i = 0; i < csVCDs.length; i++) {
//			schedule.addCalendarDay(csCDs[i], csVCDs[i]);
//		}
//		
//		
//		
//		List list2 = TestDataProvider.getTestSubjectEvents();
//		final CSSubjectEventDTO[] csSEs = (CSSubjectEventDTO[])list2.get(0);
//		final CSVSubjectEventDTO[] csvSEs = (CSVSubjectEventDTO[])list2.get(1);
//		
//		
//		for (int i = 0; i < csSEs.length; i++) {
//			schedule.addSubjectEvent(csSEs[i], csvSEs[i]);
//		}
		
		
		
		
	
//		CSGroupDTO csG = Cache.getCSGroupDTOByID(groupID.longValue());
//		
//		CSVGroupDTO csvG = ViewDataProvider.getCSVGroup(csG);
//		schedule.setHeaderText("Group View: <b>" + csvG.toLabel() + "</b>");

//		SchedulesList.downloadCSLecturerPreferences(schedule, new Long(1), new Long(1));
		
//		LecturerPreferencesDTO dto = new LecturerPreferencesDTO(1, 2, 500);
//		
//		schedule.addLecturerPreferences(dto);
//		schedule
//		disableSelection(schedule.getElement());
		
		
		RootPanel.get().add(scheduleWrapper);
//		
//		
//		Button listSEButton = new Button("listSE");
//		listSEButton.addClickListener(new ClickListener() {
//			public void onClick(Widget sender) {
//				for (int i = 0; i < csvSEs.length; i++) {
//					Planner.log("Planner.scheduleTest: " + i + ": " + csvSEs[i]);
//				}
//			}
//		});
//		RootPanel.get().add(listSEButton);
//		
//		
//		Button showFreeButton = new Button("showFree");
//		showFreeButton.addClickListener(new ClickListener() {
//			public void onClick(Widget sender) {
//				schedule.showLocationsForSubjectEvents();
//				
//				for (int i = 0; i < csvSEs.length; i++) {
//					Planner.log("Planner.scheduleTest: " + i + ": " + csvSEs[i]);
//				}
//			}
//		});
//		RootPanel.get().add(listSEButton);
//		RootPanel.get().add(showFreeButton);
		
		
//		RootPanel.get().add();
//		RootPanel.get().add(new Label("asdasdas"));
	}
	
	public void driTest() {
		RootPanel.get().add(new SemesterSelectionTreeWidget());
	}
	
	public void treeTest() {
		
		
//		Directory dir = new Directory();
//		dir.setDirName("Groups");
//		dir.addChild()
		
		
		
		Cache.loadInitialData();
		
		final TreeItem groupsTI = new TreeItem("Groups");
		final TreeItem lecturersTI = new TreeItem("Lecturers");
		final TreeItem roomsTI = new TreeItem("Rooms");
		
		
		

		Tree tree = new Tree();
		tree.addItem(groupsTI);
		tree.addItem(lecturersTI);
		tree.addItem(roomsTI);
		
		
		
		tree.addTreeListener(new TreeListener() {
			public void onTreeItemSelected(TreeItem item) {
				if (item == groupsTI && groupsTI.getChildCount() <= 0) {
					
					
					CSGroupDTO[] groups = Cache.getAllGroups();
					
					
					
					
					Sorter sorter = new Sorter();
					for (int i = 0; i < groups.length; i++) {
						sorter.addItem(groups[i].getName(), groups[i]);
					}
					sorter.sortWithAlphabeticalOrder();
					List<Object> objects = sorter.getListWithObjects();
					groups = objects.toArray(groups);

					
					
					Planner.log("Planner.treeTest: " + "TYLE MAMA GRUP " + groups.length);
					
					for (int i = 0; i < groups.length; i++) {
						final CSGroupDTO csG = groups[i];
						CSVGroupDTO csvG = ViewDataProvider.getCSVGroup(csG);
						
						final CSObjectHTML groupHTML = new CSObjectHTML(csG);
						

						
						TreeItem gTI = new TreeItem(groupHTML);
						
						String text = "" + csvG.toLabelShort();
						groupHTML.setText(text);
						
						//wczytanie podzialu na klik
						groupHTML.addClickListener(new ClickListener() {
							public void onClick(Widget sender) {
								CSSemestersYearGroupsDTO csSYG = Cache.getCSSemestersYearGroupsDTOByID(csG.getSemestersYearGroupID());
								Long semesterID = new Long(csSYG.getSemesterID());
								Long groupID = new Long(csG.getId());
								
								
								MinimizableSimplePanel scheduleWrapper = new MinimizableSimplePanel();
//								Planner.getMainHSP().setRightWidget(scheduleWrapper);
								
								CSGroupDTO csG = Cache.getCSGroupDTOByID(groupID.longValue());
								CSVGroupDTO csvG = ViewDataProvider.getCSVGroup(csG);
								String tabLabel = csvG.toLabelShort();			
								
								
								Planner.getTabPanel().add(scheduleWrapper, "" + tabLabel);
								
								SchedulesList.displayScheduleGroupView(scheduleWrapper, groupID, semesterID, null);
							}
						});

						groupsTI.addItem(gTI);
					}

				} else if (item == lecturersTI) {
					//////////////////////////////////////
					
					CSLecturerDTO[] lecturers = Cache.getAllLecturers();
					
					Sorter sorter = new Sorter();
					for (int i = 0; i < lecturers.length; i++) {
						sorter.addItem(lecturers[i].getSurname(), lecturers[i]);
					}
					sorter.sortWithAlphabeticalOrder();
					List<Object> objects = sorter.getListWithObjects();
					lecturers = objects.toArray(lecturers);
					
					
					Planner.log("Planner.treeTest: " + "TYLE MAM LECTURERSOW " + lecturers.length);
					
					for (int i = 0; i < lecturers.length; i++) {
						final CSLecturerDTO csL = lecturers[i];
						CSVLecturerDTO csvL = ViewDataProvider.getCSVLecturer(csL);
						
						final CSLecturerHTML lecturerHTML = new CSLecturerHTML(csL);
						
						
						TreeItem lTI = new TreeItem(lecturerHTML);
						
						String text = "" + csvL.toLabelShort();
						lecturerHTML.setText(text);
						
						//wczytanie podzialu na klik
						lecturerHTML.addClickListener(new ClickListener() {
							public void onClick(Widget sender) {
//								CSSemestersYearGroupsDTO csSYG = Cache.getCSSemestersYearGroupsDTOByID(csG.getSemestersYearGroupID());
//								Long semesterID = new Long(csSYG.getSemesterID());
//								Long groupID = new Long(csG.getId());
//								
//								
//								SimplePanel scheduleWrapper = new SimplePanel();
////								Planner.getMainHSP().setRightWidget(scheduleWrapper);
//								
//								CSGroupDTO csG = Cache.getCSGroupDTOByID(groupID.longValue());
//								CSVGroupDTO csvG = ViewDataProvider.getCSVGroup(csG);
//								String tabLabel = csvG.toLabelShort();			
//								
//								
//								Planner.getTabPanel().add(scheduleWrapper, "" + tabLabel);
//								
//								SchedulesList.displayScheduleGroupView(scheduleWrapper, groupID, semesterID);

								
								
								
								MinimizableSimplePanel scheduleWrapper = new MinimizableSimplePanel();
//							Planner.getMainHSP().setRightWidget(scheduleWrapper);
								
							//////////LECTURER////////////
							Long semesterID = new Long(1);
							Long lecturerID = new Long(csL.getId());
							
							
							CSLecturerDTO csL = Cache.getCSLecturerDTOByID(lecturerID.longValue());
							CSVLecturerDTO csvL = ViewDataProvider.getCSVLecturer(csL);
							String tabLabel = csvL.toLabelShort();
							
							
							Planner.getTabPanel().add(scheduleWrapper, "" + tabLabel);
							
							SchedulesList.displayScheduleLecturerPreferencesView(scheduleWrapper, lecturerID, semesterID);
								
								
								
							}
						});

						lecturersTI.addItem(lTI);
					}
					
					
				}
				
				
				
			}
			public void onTreeItemStateChanged(TreeItem item) {
				// TODO Auto-generated method stub
				
			}
		});
				
		RootPanel.get().add(tree);
	}
	
	
	public void treeWidget() {
		Tree tree = new Tree();
		TreeItem ti = new TreeItem("jakis string");
		ti.setHeight("10px");
		TreeItem ti1 = new TreeItem("1");
		TreeItem ti2 = new TreeItem("2");
		ti.addItem(ti1);
		ti.addItem(ti2);
		TreeItem ti12 = new TreeItem("12");
		TreeItem ti13 = new TreeItem("13");
		
		ti1.addItem(ti12);
		ti1.addItem(ti13);
		
		tree.addItem(ti);
		
		
		RootPanel.get().add(tree);
	}

	public void createDeclarationDialog() {
		Cache.loadInitialData();
		CreateSubjectEventDialog csed = new CreateSubjectEventDialog();
		RootPanel.get().add(csed);
	}
	
	public void testHSPInTabPanel() {
		TabPanel tp = new TabPanel();
		tp.setWidth("600px");
		tp.setHeight("300px");

		JPHorizontalSplitPanel hsp = new JPHorizontalSplitPanel();

		HTML leftHTML  = new HTML("left widget");
		leftHTML.setPixelSize(200, 200);
		leftHTML.setStyleName("test");
		HTML rightHTML  = new HTML("right widget");
		rightHTML.setPixelSize(200, 200);
		rightHTML.setStyleName("test");

		hsp.setLeftWidget(leftHTML);
		hsp.setRightWidget(rightHTML);
		tp.add(hsp, "hsp tab");
		
		hsp.setSplitPosition(60);
		hsp.setHeight("100px");
		
		RootPanel.get().add(tp);
	}
	

	
	
	
	public void rebuildGUI(String msg, boolean firstTimeStartup) {
		
		if (isItFirstRebuildingGUI) {
			schedulesList = new SchedulesList();
			
			
			isItFirstRebuildingGUI = false;
		}
		
		
		
		resetGUI();
//		Cache.clearAllStoredData();
		
		
		
		
		showLoadingMessage(msg, true, null);
		
		
		setupDatabaseVP();
		setupStackPanel();
		setupTop();
		setupMainHSP();
		setupMainVSP();
		setup();
//		setupLogPanel();
		
		Window.enableScrolling(false);
		
		
		
  		topHTML.setWidth(Window.getClientWidth() - 10 +"px");
  		
//  		topHTML.setHeight(TOP_HTML_HEIGHT+"px");
  		
  		stackPanel.setWidth(STACK_PANEL_WIDTH+"px");
  		stackPanel.setHeight((Window.getClientHeight() - TOP_HTML_HEIGHT - 17)+"px");
  		
  		mainHSP.setWidth(Window.getClientWidth()+"px");
  		mainHSP.setHeight((Window.getClientHeight() - TOP_HTML_HEIGHT - 17)+"px");
		
  		tabPanel.setWidth("800px");
  		tabPanel.setHeight("400px");
  		tabPanel.setAnimationEnabled(true);
		
		//splitPanelExample();
  		if (windowResizeListener == null) {
  			windowResizeListener = new WindowResizeListener() {
  				public void onWindowResized(int width, int height) {
  					resizeApplicationWindow(width, height);
  				}
  			};
  			Window.addWindowResizeListener(windowResizeListener);
  		}
		resizeApplicationWindow(Window.getClientWidth(), Window.getClientHeight());
		
		mainHSP.setSplitPosition(200);
		mainVSP.setSplitPosition(TOP_HTML_HEIGHT);
		
		
		
		if (firstTimeStartup) {
			PCompositeRequestBuilder b = Cache.loadInitialData();
//			RootPanel.get().add(b.generateStatusWidget(), 10, 10);
			b.makeAllCalls();
			
//			Cache.loadInitialData();
		} else {
			Cache.loadDataWhenAnotherSemesterSelected();
		}
		
	}

	/**
	 * 
	 */
	private void resetGUI() {
		//resetGUI
//		databaseVP.clear();
		stackPanel.clear();
		
		topAP.clear();
		topVP.clear();
		contextSemesterSB.clear();
		tabPanel.clear();
	}
	
	
	public void testJPHorizontalSplitPanel() {
		final JPHorizontalSplitPanel splitPanel = new JPHorizontalSplitPanel();
		RootPanel.get().add(splitPanel);
		
		final Label label1 = new Label("qwertyuiopqwertyuiop");
		
		Button button = new Button("change");
		button.addClickListener(new ClickListener(){
			public void onClick(Widget sender) {
				splitPanel.setLeftWidget(label1);
				splitPanel.showOrHideFirstWidget();
				splitPanel.setHeight("400px");
				splitPanel.setWidth("400px");
			}
		});
		RootPanel.get().add(button);
	}

	public void testJPVerticalSplitPanel() {
		final JPVerticalSplitPanel splitPanel = new JPVerticalSplitPanel();
		RootPanel.get().add(splitPanel);
		
		final Label label1 = new Label("qwertyuiopqwertyuiop");
		
		Button button = new Button("change");
		button.addClickListener(new ClickListener(){
			public void onClick(Widget sender) {
				splitPanel.setTopWidget(label1);
				splitPanel.showOrHideFirstWidget();
				splitPanel.setHeight("400px");
				splitPanel.setWidth("400px");
			}
		});
		RootPanel.get().add(button);
	}
	
	public void setupDatabaseVP() {
		
		
	}
	
	public void setupStackPanel(){
		
		final ScrollPanel scheduleScrollPanel = new ScrollPanel();
		final VerticalPanel scheduleVP = new VerticalPanel();
		
		final SimplePanel sp = new SimplePanel(); 
		
	
		sp.setWidget(schedulesList);

		scheduleVP.add(sp);
		scheduleScrollPanel.add(scheduleVP);
		
		String scheduleCode = "<span class='stackPanelItem-Schedules'/>SCHEDULES</span>";
		
	
		
		stackPanel.add(scheduleScrollPanel, scheduleCode, true);
	
		if (ContextSettings.isAdminUserSignedIn()) {
			final ScrollPanel databaseScrollPanel = new ScrollPanel();
			databaseScrollPanel.add(databaseVP);
			
			String databaseCode = "<span class='stackPanelItem-Database'/>DATABASE</span>";
			stackPanel.add(databaseScrollPanel, databaseCode, true);
		}
		
	}
	
	

	public void setupTop() {
		topHTML.setStyleName(STYLE_TOPHTML);
		
		topVP.add(topHTML);
		topVP.add(contextSemesterSB);
		
		contextSemesterSB.setWidth(290+"px");
		contextSemesterSB.setItemsPanelWidth(340);

		
		contextSemesterSB.addChangeListener(new ChangeListener() {
			public void onChange(Widget sender) {
				CSSemesterDTO csS = (CSSemesterDTO)contextSemesterSB.getSelectedObject();
				switchSemesterWithGivenID(csS.getId());
			}
		});
		
		loadDataToSemesterSelectionWidget();
		
		
		if (ContextSettings.isAdminUserSignedIn()) {
			
			HorizontalPanel linksHP = new HorizontalPanel();
			linksHP.setSpacing(4);
			
			HTML createNewSemesterB = new HTML("<span class='plan-Link'>Add</span></center>");
			
//		Button createNewSemesterB = new Button("Create new semester");
			createNewSemesterB.addClickListener(new ClickListener() {
				public void onClick(Widget sender) {
//				CSSemesterDTO csS = Cache.getCSSemesterDTOByID(ContextSettings.getSemesterID());
					CreateSemesterDialog csd = new CreateSemesterDialog(null, contextSemesterSB); 
					csd.center();
				}
			});
			
			HTML editSelectedSemesterB = new HTML("<span class='plan-Link'>Edit</span></center>");
			editSelectedSemesterB.addClickListener(new ClickListener() {
				public void onClick(Widget sender) {
					CSSemesterDTO csS = Cache.getCSSemesterDTOByID(ContextSettings.getSemesterID());
					CreateSemesterDialog csd = new CreateSemesterDialog(csS, contextSemesterSB); 
					csd.center();
				}
			});
			
			
			HTML removeSelectedSemesterB = new HTML("<span class='plan-Link'>Remove</span></center>");
//		Button removeSelectedSemesterB = new Button("Remove selected semester");
			removeSelectedSemesterB.addClickListener(new ClickListener() {
				public void onClick(Widget sender) {
					
					final CSSemesterDTO csS = (CSSemesterDTO)contextSemesterSB.getSelectedObject();
					if (csS == null) {
						Window.alert("Semester not selected.");
					} else {
						Planner.log("removeSelectedSemester.onClick: " + "usuwam semester, id: " + csS.getId());
						
						AsyncCallback<Boolean> callback = new AsyncCallback<Boolean>() {
							public void onFailure(Throwable caught) {
								Planner.log("Planner.removeSelectedSemester() FAILURE: " + "");
							}
							public void onSuccess(Boolean res) {
								Planner.log("Planner.removeSelectedSemester() SUCCESS -> zwrocone wynik = " + res);
								
								if (res.booleanValue()) {
									
									contextSemesterSB.removeObjectWithID(csS.getId());
									//update w cache
									Cache.removeCSSemester(csS);
									switchSemesterWithGivenID(csS.getId());
									
								} else {
									Window.alert("Selected semester not removed.");
								}
								
							}
						};
						
						ServiceHolder.get().removeCSSemester(csS, callback);
						
					}
					
				}
			});
			
			
			HTML setAsDefaultSelectedSemesterB = new HTML("<span class='plan-Link'>Set as defalt</span></center>");
			setAsDefaultSelectedSemesterB.addClickListener(new ClickListener() {
				public void onClick(Widget sender) {
					CookiesSettings.setDefaultSemesterForAdmin(ContextSettings.getSemesterID());
				}
			});
			
			linksHP.add(createNewSemesterB);
			linksHP.add(editSelectedSemesterB);
			linksHP.add(removeSelectedSemesterB);
			topVP.add(linksHP);
			
		}
		
		
		topAP.add(topVP);
		signInWidgets = new SignInWidgets();
		topAP.add(signInWidgets);
	}
	
	
	/**
	 * @param csS
	 */
	private void switchSemesterWithGivenID(long id) {
		ContextSettings.setSemesterID(id);
		Planner.log("Planner.setupTop.onChange: " + "wybrano semester " + id);
		
		tabPanel.clear();
		
		schedulesList.markBranchWithGroupSchedulesAsLoading();
		Planner.get().showLoadingMessage("Switching semester...", true, null);
		
		Cache.loadDataWhenAnotherSemesterSelected();
	}

	
	
	/**
	 * TO WYRZUCIC DO CACHE
	 */
	public void loadDataToSemesterSelectionWidget() {
		
		Planner.log("Planner.loadDataToSemesterSelectionWidget: ...");
		
		if (Cache.containsAllSemesterData()) {
			
			CSSemesterDTO[] ss = Cache.getAllSemesters();
			
			if (ss == null) {
				Planner.log("Planner.loadDataToSemesterSelectionWidget: " + "mamy NULLa");
			}
			
			Sorter sorter = new Sorter();
			for (int i = 0; i < ss.length; i++) {
				String ssLabel = ViewDataProvider.getCSVSemester(ss[i]).toLabelForSorting(); 
				sorter.addItem(ssLabel, ss[i]);
			}
			sorter.sortWithAlphabeticalOrder();
			List<Object> objects = sorter.getListWithObjects();
			ss = objects.toArray(ss);
			
			
			contextSemesterSB.clear();
			
			for (int i = 0; i < ss.length; i++) {
				
				if (ContextSettings.isAdminUserSignedIn() || ss[i].isVisibleForOrdinaryUsers() ) {
					
					CSVSemesterDTO csvS = ViewDataProvider.getCSVSemester(ss[i]);
					String label = csvS.toLabel();
					
					contextSemesterSB.addItem(label, ss[i]);
					
					if (ContextSettings.getSemesterID() == ss[i].getId()) {
						contextSemesterSB.setSelectedIndex(contextSemesterSB.getItemCount()-1);
					}
					
				}
				
			}
			
		}
	}
	

	public void setupMainHSP() {
		//  mainHSP.setStyleName(STYLE_MAINHSP);
		  mainHSP.setLeftWidget(stackPanel);
		  
		  mainHSP.setRightWidget(tabPanel);
		  tabPanel.add(new Label("Welcome to Academic Planner!"), "Welcome", "WELCOME");
	}

	public void setupMainVSP() {
		//mainVSP.setStyleName(STYLE_MAINVSP);
		mainVSP.setTopWidget(topAP);
		mainVSP.setBottomWidget(mainHSP);
	}

	public void setupLogPanel() {
//		logger = new LogPanel();
//		stackPanel.add(logger, "L O G S ");
//		stackPanel.showStack(2);
	}
	
  	public void setup() {
  		RootPanel.get().add(mainVSP);
  		resizeApplicationWindow(Window.getClientWidth(), Window.getClientHeight());
  	}
  
  
  	public void resizeApplicationWindow(int width, int height) {
  		mainVSP.setWidth(width+"px");
  		mainVSP.setHeight(height+"px");
  		
  		//mainVSP.setSplitPosition(TOP_HTML_HEIGHT);
  	}
  
  public void splitPanelExample() {
	  final DraggableZone dz1 = new DraggableZone();
	  final DraggableZone dz2 = new DraggableZone();
	  
	  dz1.setWidth("200px");
	  dz1.setHeight("300px");
	  dz2.setWidth("200px");
	  dz2.setHeight("300px");

	  final JPHorizontalSplitPanel hsp = new JPHorizontalSplitPanel();
	  hsp.setLeftWidget(dz1);
	  hsp.setRightWidget(dz2);
	  hsp.setWidth("800px");
	  RootPanel.get().add(hsp);
	  
	  
	  Button b = new Button("kk");
	  b.addClickListener(new ClickListener(){
		 public void onClick(Widget sender) {
			Window.alert("aaa " + dz1.getOffsetWidth());
			
		} 
	  });
	  RootPanel.get().add(b);
	  
	  
  }
  
  public void testDecoratedTabPanel() {
	  DecoratedTabPanel dtp = new DecoratedTabPanel();
	  RootPanel.get().add(dtp, 100, 100);

	  HTML tabWidget = new HTML("cyan");
	  dtp.add(new Label("cyainde"), tabWidget);
	  
	  
	  HTML tabWidget2 = new HTML("cyan2");
	  dtp.add(new Label("cyainde2"), tabWidget2);

  }
  
  
  public static void displayToolTip(ToolTip toolTip, int x, int y) {
	  
	  if (displayedToolTip != null && displayedToolTip != toolTip) {
		  //remove attached different tooltip
		  RootPanel.get().remove(displayedToolTip);
	  } else if (displayedToolTip != null) {
		  //replace attached widget
		  RootPanel.get().setWidgetPosition(toolTip, x, y);
		  return;
	  }
	  
	  //attach new tooltip
	  displayedToolTip = toolTip;
	  RootPanel.get().add(toolTip, x, y);
  }
  
  public static void hideToolTip() {
	  if (displayedToolTip != null) {
		  RootPanel.get().remove(displayedToolTip);
		  displayedToolTip = null;
	  }
  }
  
  public static boolean isToolTipDisplayed() {
	  return (displayedToolTip != null)?true:false;
  }
  
  public static void setToolTipPosition(int x, int y) {
	  if (displayedToolTip != null) {
		  RootPanel.get().setWidgetPosition(displayedToolTip, x, y);
	  }
  }
  
  public static void logOld(String msg) {
	  if (logger != null) {
		  logger.log(msg);
	  }
  }
  
  public static void log(String msg) {
	  if (GWT.isScript() && ContextSettings.isFirebugDebugMode()) {
		  NativeJS.logToFirefoxConsole(msg);
//		  NativeJS.logToFirefoxConsoleDebug(msg);
//		  NativeJS.logToFirefoxConsoleInfo(msg);
//		  NativeJS.logToFirefoxConsoleWarn(msg);
//		  NativeJS.logToFirefoxConsoleError(msg);
	  } else {
		  GWT.log(msg, null);
	  }
  }
  
	public static JPHorizontalSplitPanel getMainHSP() {
		return mainHSP;
	}
  
	public static MinimizableTabPanel getTabPanel() {
		return tabPanel;
	}

	public void tabsTest() {
		TabPanel tp = new TabPanel();
		for (int i = 0; i < 20; i++) {
			tp.add(new Label("text " + i), "text tttt " + i);
			
		}
		RootPanel.get().add(tp);
		
	}
	
	public static Planner get() {
		return planner;
	}

	public static native void clearSelection() /*-{
	  $wnd.clearSelection();
	}-*/;
	
	public static native void disableSelection(Element element) /*-{
	  $wnd.disableSelection(element);
	}-*/;

	public SchedulesList getSchedulesList() {
		return schedulesList;
	}
	
	public void showLoadingMessage(String msg, boolean showLoader, Widget widget) {
		if (mainLoaderBackground != null) {
			mainLoaderBackground.removeFromParent();
		}
		mainLoaderBackground = new LoaderBackground();
		mainLoaderBackground.setWidth((Window.getClientWidth()+20) + "px");
		mainLoaderBackground.setHeight((Window.getClientHeight()+20) + "px");
		
		RootPanel.get().add(mainLoaderBackground, 0, 0);
		
		VerticalPanel loaderVP = new VerticalPanel();
		loaderVP.setSpacing(30);
		
		if (showLoader) {
			//kreciolek
			Loader loader = new Loader(LoaderSizes.LOADER_MAIN);
			loaderVP.add(loader);
			loaderVP.setCellHorizontalAlignment(loader, HasHorizontalAlignment.ALIGN_CENTER);
		}
		

		if (msg != null) {
			//msg
			HTML loaderMsgHTML = new HTML(msg);
			loaderVP.add(loaderMsgHTML);
			loaderVP.setCellHorizontalAlignment(loaderMsgHTML, HasHorizontalAlignment.ALIGN_CENTER);
		}
		
		if (widget != null) {
			loaderVP.add(widget);
			loaderVP.setCellHorizontalAlignment(widget, HasHorizontalAlignment.ALIGN_CENTER);
		}
		
		
		mainLoaderBackground.add(loaderVP);
		
		int left = Window.getClientWidth()/2 - loaderVP.getOffsetWidth()/2;
		int top = Window.getClientHeight()/2 - loaderVP.getOffsetHeight()/2;
		mainLoaderBackground.setWidgetPosition(loaderVP, left, top);
	}
	
	public static void fadeWidgetWithMsg(String msg, boolean showLoader, CustomDialogBox w) {
		if (fadingLoader != null) {
			fadingLoader.removeFromParent();
		}
		fadingLoader = new LoaderBackground();
		fadingLoader.setWidth(Window.getClientWidth() + "px");
		fadingLoader.setHeight(Window.getClientHeight() + "px");
		
		RootPanel.get().add(fadingLoader, 0, 0);
		
		VerticalPanel loaderVP = new VerticalPanel();

		if (showLoader) {
			//kreciolek
			Loader loader = new Loader(LoaderSizes.LOADER_MAIN);
			loaderVP.add(loader);
			loaderVP.setCellHorizontalAlignment(loader, HasHorizontalAlignment.ALIGN_CENTER);
		}
		
		if (msg != null) {
			//msg
			HTML loaderMsgHTML = new HTML(msg);
			loaderVP.add(loaderMsgHTML);
			loaderVP.setCellHorizontalAlignment(loaderMsgHTML, HasHorizontalAlignment.ALIGN_CENTER);
		}
		
		loaderVP.setSpacing(30);
		
		fadingLoader.add(loaderVP);

		w.center();
//		int left = w.getAbsoluteLeft() + w.getOffsetWidth()/2 - loaderVP.getOffsetWidth()/2;
//		int top = w.getAbsoluteTop() + w.getOffsetHeight()/2 - loaderVP.getOffsetHeight()/2;
//		fadingLoader.setWidgetPosition(loaderVP, left, top);
	}
	
	public void hideLoadingMessage() {
		if (mainLoaderBackground != null) {
			mainLoaderBackground.removeFromParent();
			mainLoaderBackground = null;
		}
	}

	public void hideFading() {
		if (fadingLoader != null) {
			fadingLoader.removeFromParent();
			fadingLoader = null;
		}
	}
	
	public void runOnSignInAdminUser(String login) {
		ContextSettings.setSignedInAdminUserLogin(login);
		boolean firstTimeStartup = false;
		Planner.get().rebuildGUI("Signing in. Please wait...", firstTimeStartup);
		signInWidgets.rebuildOnSignIn(login);
	}
	
	public void runOnSignOutAdminUser() {
		ContextSettings.setSignedInAdminUserLogin(null);
		boolean firstTimeStartup = false;
		Planner.get().rebuildGUI("Signing out. Please wait...", firstTimeStartup);
		signInWidgets.rebuildOnSignOut();
	}	

}
